<?php

function getByteAuthorization($url, $data, $appId, $nonceStr, $timestamp, $keyVersion)
{
   $byteAuthorization = '';
   // 读取私钥
   $privateKeyStr = file_get_contents("../private_key.pem");

   $privateKey = openssl_pkey_get_private($privateKeyStr);

   if (!$privateKey) {
      throw new InvalidArgumentException("Invalid private key");
   }
   // 生成签名
   $signature = getSignature("POST", $url, $timestamp, $nonceStr, $data, $privateKey);
   if ($signature === false) {
      return null;
   }

   // 构造 byteAuthorization
   $byteAuthorization = sprintf("SHA256-RSA2048 appid=%s,nonce_str=%s,timestamp=%s,key_version=%s,signature=%s", $appId, $nonceStr, $timestamp, $keyVersion, $signature);

   return $byteAuthorization;
}

function getSignature($method, $url, $timestamp, $nonce, $data, $privateKey)
{
   $targetStr = $method . "\n" . $url . "\n" . $timestamp . "\n" . $nonce . "\n" . $data . "\n";
   openssl_sign($targetStr, $sign, $privateKey, OPENSSL_ALGO_SHA256);
   $sign = base64_encode($sign);
   return $sign;
}

function randStr($length = 8)
{
   $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
   $str = '';
   for ($i = 0; $i < $length; $i++) {
      $str .= $chars[mt_rand(0, strlen($chars) - 1)];
   }
   return $str;
}

function sign_post($url, $byteAuthorization, $data)
{
 
   $curl = curl_init();
   curl_setopt_array($curl, [
      CURLOPT_URL => $url,
      CURLOPT_RETURNTRANSFER => true,
      CURLOPT_ENCODING => "",
      CURLOPT_MAXREDIRS => 10,
      CURLOPT_TIMEOUT => 30,
      CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
      CURLOPT_CUSTOMREQUEST => "POST",
      CURLOPT_POSTFIELDS => $data,
      CURLOPT_HTTPHEADER => [
         "Content-Type: application/json",
         'Byte-Authorization: ' . $byteAuthorization
         // 'Byte-Authorization: SHA256-RSA2048 appid="ttdd96ab2b42a07b6d01",nonce_str="nGgXNFyZfsu",timestamp="1719889433",key_version="3",signature="KHnNsAYFKF+1Fsg26EwgNw/ITUp1UvsvlZ5QQqVzLJIDbtFsBGFlOx8xneH4tgP/0ZWuHP3XD2IuZheGPgeRltAwrTkO7UYQJd7Ob4LvCRPUQflo7cc7Zo+A5RMIaijicQDJkIpZphB67nYwSQvUqziI3h4XNJ5OD7lwaDt/LE+FsOIAmjLd5ZxN/780kqYvg68AShQXuTzugP+SftVnk+CRulmG2Sa+D2X3vD+yqzSraI/OdKCy2AecxDwL4rUnmufBPlTk3oL4LHd8fx/dmWvrHTYkAqN2JBdzj7dZEPD0RW0kUqpPtHpTW1hqGQwbVfBT1OMv9RAwAqGWCKr3DQ=="'
      ],
   ]);

   $response = curl_exec($curl);
   $err = curl_error($curl);
   curl_close($curl);

   if ($err) {
      return "cURL Error #:" . $err;
   } else {
      return $response;
   }
}

